#include "../../include/chat_tool.h"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/epoll.h>
void chatroom_tool::init(int open_port, const char user[], const char passwd[], const char db[])
{
    Mysql.init(user, passwd, db);
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1)
    {
        cout << "套接字创建失败" << endl;
        return;
    }
    else
    {
        cout << "套接字创建成功" << endl;
    }
    gun_like.init(mysql);
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(open_port);
    saddr.sin_addr.s_addr = (INADDR_ANY);
    int opt = 1;
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const void *)&opt, sizeof(opt));
    int rec = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
    if (rec != 0)
    {
        cout << rec << endl;
        cout << "绑定失败" << endl;
        return;
    }
    else
    {
        cout << "绑定成功" << endl;
    }
    rec = listen(fd, 1);
    if (rec != 0)
    {
        cout << "监听失败" << endl;
    }
    else
        cout << "监听成功" << endl;
    epfd = epoll_create(1);
    if (epfd == -1)
    {
        cout << "epoll生成失败" << endl;
        return;
    }
    else
    {
        cout << "epoll生成成功" << endl;
    }
    struct epoll_event ev;
    ev.events = EPOLLIN;
    ev.data.fd = fd;
    int temp = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
    if (temp == -1)
    {
        cout << "epoll函数失败" << endl;
    }
    else
    {
        cout << "epoll函数成功" << endl;
    }
    size = sizeof(evs) / sizeof(evs[0]);
    cout << fd << endl;
}